package com.wy.demo.service.impl;

import org.bytedeco.javacv.FFmpegFrameGrabber;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.math.RoundingMode;

public class aaa {
    // FFmpeg路径配置
    private static final String FFMPEG_PATH = "D:\\study_soft\\ffmpeg\\ffmpeg-7.0.2-essentials_build\\bin\\ffmpeg.exe";

    /**
     * 将视频平均分割成N段
     *
     * @param inputPath 输入视频路径
     * @param segments 需要分割的段数
     * @return 是否分割成功
     */
    public boolean splitVideo(String inputPath, int segments) {
        if (segments <= 0) {
            System.err.println("分段数必须大于0");
            return false;
        }

        try {
            // 1. 获取视频信息
            FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(inputPath);
            grabber.start();
            
            // 获取视频总时长（秒）
            double duration = grabber.getLengthInTime() / 1000000.0; // 微秒转秒
            grabber.close();
            
            // 2. 计算每段时长
            double segmentDuration = duration / segments;
            
            // 格式化时长为两位小数
            DecimalFormat df = new DecimalFormat("0.00");
            df.setRoundingMode(RoundingMode.HALF_UP);
            String formattedDuration = df.format(segmentDuration);
            
            // 3. 生成输出文件名模板
            File inputFile = new File(inputPath);
            String parentPath = inputFile.getParent();
            String fileName = inputFile.getName();
            String nameWithoutExt = fileName.substring(0, fileName.lastIndexOf('.'));
            
            System.out.println("开始分割视频...");
            System.out.println("视频总时长: " + df.format(duration) + " 秒");
            System.out.println("分割段数: " + segments);
            System.out.println("每段时长: " + formattedDuration + " 秒");
            
            // 4. 使用FFmpeg进行分割
            for (int i = 0; i < segments; i++) {
                String outputPath = new File(parentPath, 
                    String.format("%s_part%d.mp4", nameWithoutExt, (i + 1))).getAbsolutePath();
                
                double startTime = i * segmentDuration;
                
                ProcessBuilder pb = new ProcessBuilder(
                    FFMPEG_PATH,
                    "-i", inputPath,
                    "-ss", df.format(startTime),              // 开始时间
                    "-t", formattedDuration,                  // 持续时间
                    "-c:v", "copy",                           // 复制视频流
                    "-c:a", "copy",                           // 复制音频流
                    "-avoid_negative_ts", "1",                // 避免负时间戳
                    outputPath
                );
                
                System.out.println("\n处理第 " + (i + 1) + "/" + segments + " 段");
                System.out.println("开始时间: " + df.format(startTime) + " 秒");
                System.out.println("输出文件: " + outputPath);
                
                // 将错误输出重定向到标准输出
                pb.redirectErrorStream(true);
                
                // 启动进程
                Process process = pb.start();
                
                // 读取输出
                BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                String line;
                while ((line = reader.readLine()) != null) {
                    System.out.println(line);
                }
                
                // 等待进程完成
                int exitCode = process.waitFor();
                if (exitCode != 0) {
                    System.err.println("分割第 " + (i + 1) + " 段失败");
                    return false;
                }
            }
            
            System.out.println("\n=== 视频分割完成 ===");
            System.out.println("共分割: " + segments + " 段");
            System.out.println("输出目录: " + parentPath);
            
            return true;
            
        } catch (Exception e) {
            System.err.println("分割视频时出错: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    // 使用示例
    public static void main(String[] args) {
        aaa processor = new aaa();
        String videoPath = "C:\\Users\\wy\\Desktop\\222\\555.mp4";
        boolean success = processor.splitVideo(videoPath, 3);
        if (success) {
            System.out.println("视频分割成功！");
        } else {
            System.out.println("视频分割失败！");
        }
    }
}
